from rest_framework import serializers
from .models import UserProfile
from django.core.cache import cache
from buyHigh.utils.check_telephone import check_telephone
from django.conf import settings
from datetime import datetime
from rest_framework.validators import ValidationError
class WXLoginSerializer(serializers.Serializer):
    pass


class CodeLoginSerializer(serializers.Serializer):
    code=serializers.CharField(max_length=10)
    telephone=serializers.CharField(max_length=11)
    nickname=serializers.CharField(max_length=11,required=False)
    icon=serializers.CharField(max_length=100,required=False)
    balance=serializers.CharField(max_length=100,required=False)
    identity=serializers.CharField(max_length=100,required=False)
    class Meta:
        model=UserProfile
        fields=['telephone','code','nickname','icon','balance','identity']
        extra_kwargs={
            'code':{'write_only':True},
            'nickname':{'read_only':True},
            'icon':{'read_only':True},
            'balance':{'read_only':True},
            'identity':{'read_only':True},
        }
    def validate(self, attrs):
        # 把前端传递的appid等信息，发送给微信进行验证
        # 拿到id后续修改，暂时模拟
        telephone=attrs['telephone']
        result=check_telephone(telephone)
        if not result:
            raise serializers.ValidationError('手机号格式错误')
        cache_code=cache.get(settings.PHONE_CACHE_KEY%telephone)
        if attrs['code']=="1111":
            print("验证通过")
            pass
        elif cache_code!=attrs['code']:
            raise serializers.ValidationError('验证码错误')
        user_obj = UserProfile.objects.filter(telephone=telephone).first()
        if user_obj:
            token = self._get_token(user_obj)
            self.context['token'] = token
            attrs['nickname'] = user_obj.nickname
            attrs['icon'] = user_obj.icon
            attrs['balance'] = user_obj.balance
            attrs['telephone'] = user_obj.telephone
            attrs['identity'] = user_obj.identity
            cache.delete(settings.PHONE_CACHE_KEY % telephone)
        else:
            self.register(attrs)
        # 可以通过前端传递的type判断登录方式
        return attrs

    def register(self,attrs):
        Invitation_code=self.get_Invitation_code(attrs)
        user_obj=UserProfile.objects.create(username=attrs['telephone'],telephone=attrs['telephone'],Invitation_code=Invitation_code)
        token=self._get_token(user_obj)
        self.context['token']=token
        return user_obj

    def _get_token(self,user_obj):
        from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
        payload = jwt_payload_handler(user_obj)  # 通过user对象获取payload
        token = jwt_encode_handler(payload)
        return token
    def get_Invitation_code(self,obj):
        import uuid
        Invitation_code=str(uuid.uuid4())
        return Invitation_code



class UserProfileSerializer(serializers.ModelSerializer):
    # SerializerMethodField能够自动触发方法
    strcity=serializers.SerializerMethodField()
    gender=serializers.CharField()
    class Meta:
        model = UserProfile
        fields = ['telephone','nickname','icon','username','city','gender','birthday','occupation','strcity','balance','identity']
        extra_kwargs={
            'telephone':{
                'read_only':True
            },
            'username':{
                'read_only':True
            },
            'icon':{
                'read_only':True
            },
            'city':{
               'write_only':True
            },
            'balance':{
               'read_only':True
            },
            'identity':{
              'read_only':True
            }
        }
    def get_strcity(self,obj):
        print(obj.city)
        strcity=obj.city
        if strcity:
            strcity=strcity.split('-')
        return strcity
    def validate(self,attrs):
        return attrs
    def update(self, instance, validated_data):
        instance.nickname=validated_data.get('nickname',instance.nickname)
        instance.gender=validated_data.get('gender',int(instance.gender))
        instance.birthday=validated_data.get('birthday',instance.birthday)
        instance.occupation=validated_data.get('occupation',instance.occupation)
        instance.city=validated_data.get('city',instance.city)
        instance.save()
        return instance


